/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Huynh Duy Khuong
 */
package Custom;

import java.awt.Component;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.EventObject;
import javax.swing.DefaultCellEditor;
import javax.swing.JTable;
import javax.swing.JTextField;
import Control.*;

//http://www.java2s.com/Code/Java/Swing-JFC/SettingtheActivationClickCountforaTableCellEditorinaJTableComponent.htm
public class CustomTableCellEditor extends DefaultCellEditor {

    File f = null;

    public CustomTableCellEditor(JTextField textField) {
        super(textField);
    }

    @Override
    public boolean stopCellEditing() {
        JTextField field = (JTextField)this.getComponent();
        String newName = field.getText();
        if (f != null) {
            String oldName = f.getName();

            if (newName.compareTo(oldName) != 0) {
                if (f.isFile() && !FileUtilities.haveExtension(newName)) {
                    String ext = FileUtilities.getExtension(oldName);
                    newName = FileUtilities.appendExt(newName, ext);
                }
                MiniTotalCommanderControl.rename(f, newName);
            }
        }
        return super.stopCellEditing();
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        Component cell = super.getTableCellEditorComponent(table, value, isSelected, row, column);
        if (isSelected) {
            MyLabel lb = (MyLabel) value;
            JTextField field = (JTextField) getComponent();
            field.setText(lb.getText());
            f = (File)lb.getTag();

            return cell;
        }
        return null;
    }

    @Override
    public boolean isCellEditable(EventObject evt) {
        if (evt instanceof MouseEvent) {
            MouseEvent e = (MouseEvent) evt;
            return e.getClickCount() == 1;
        }
        
        return false;
    }
}
